package com.blockchain.front.service.trading.achieve;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.UnixCrypt;

import com.blockchain.common.enums.EntrustType;
import com.blockchain.common.enums.IsPass;
import com.blockchain.common.enums.JymmType;
import com.blockchain.common.enums.JyztStatus;
import com.blockchain.framework.http.upload.FileStore;
import com.blockchain.framework.resource.ResourceNotFoundException;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.exception.LogicalException;
import com.blockchain.framework.service.exception.ParameterException;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.framework.service.query.ItemParser;
import com.blockchain.framework.service.query.Paging;
import com.blockchain.framework.service.query.PagingResult;
import com.blockchain.front.config.FrontConst;
import com.blockchain.front.service.financial.entity.JlEntity;
import com.blockchain.front.service.financial.entity.UserZhEntity;
import com.blockchain.front.service.financial.entity.WdwtEntity;
import com.blockchain.front.service.security.entity.QbdzEntity;
import com.blockchain.front.service.trading.TradingManage;
import com.blockchain.front.service.trading.entity.HqEntity;
import com.blockchain.front.service.trading.entity.KlineEntityNew;
import com.blockchain.front.service.trading.entity.PjEntity;
import com.blockchain.front.service.trading.entity.WtEntity;
import com.blockchain.front.service.trading.entity.XlbEntity;
import com.blockchain.front.service.trading.entity.XxcsEntity;
import com.blockchain.front.service.trading.entity.ZhEntity;
import com.blockchain.front.util.JsonUtil;
import com.blockchain.front.util.MD5;
import com.blockchain.util.Formater;
import com.blockchain.util.StringHelper;
import com.blockchain.util.parser.EnumParser;
import com.blockchain.util.parser.TimestampParser;
import com.blockchain.variables.P2PConst;
import com.cuohe.models.Market;

public class TradingManageImpl extends AbstractTradingService implements TradingManage {

	public static class TradingManageFactory implements ServiceFactory<TradingManage> {

		@Override
		public TradingManage newInstance(ServiceResource serviceResource) {
			return new TradingManageImpl(serviceResource);
		}
	}

	public TradingManageImpl(ServiceResource serviceResource) {
		super(serviceResource);
	}

	@Override
	public QbdzEntity[] getXlb() throws Throwable {
		StringBuffer sql = new StringBuffer("SELECT mc.F01,mc.F05,");
		sql.append(" mr.F03 ywm_c,mr.F04 zwm_c, mc.F03 ywm_r,mc.F04 zwm_r,T6015.F01,mc.F02 ywjc,mc.F28 zwm_f");
		sql.append(",T6015.F12 is_trade");
		sql.append("  FROM T6015 LEFT JOIN T6013 mr ON mr.F01=T6015.F03 ");
		sql.append("  LEFT JOIN T6013 mc ON mc.F01=T6015.F04 ");
		sql.append("  WHERE mc.F01>0 AND T6015.F13=?  ORDER BY T6015.F16 ASC");
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<QbdzEntity>() {
			ArrayList<QbdzEntity> list = new ArrayList<QbdzEntity>();

			@Override
			public QbdzEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					QbdzEntity x = new QbdzEntity();
					x.id = re.getInt(1);
					x.tblj = re.getString(2);
					x.ywm_m = re.getString(3);
					x.zwm_m = re.getString(4);
					x.ywm_s = re.getString(5);
					x.zwm_s = re.getString(6);
					x.scid = re.getInt(7);
					x.ywjc = re.getString(8);
					x.zwm_f = re.getString(9);
					x.is_trade = EnumParser.parse(IsPass.class, re.getString(10));
					if (list == null) {
						list = new ArrayList<>();
					}
					list.add(x);
				}
				return list == null ? null : list.toArray(new QbdzEntity[list.size()]);
			}
		}, sql.toString(), IsPass.S);
	}

	@Override
	public UserZhEntity getZhXlb(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		int bid = getBid(scid);
		if (bid <= 0) {
			throw new ParameterException("err_1025");
		}
		StringBuffer sql = new StringBuffer("SELECT T6025.F03 bid,T6025.F04 ky,T6025.F05 dj,");
		sql.append(" T6013.F02 ywm,T6013.F04 zwm,T6013.F05 tblj");
		sql.append(" FROM T6025 LEFT JOIN T6013 ON T6025.F03=T6013.F01");
		sql.append(" WHERE  T6025.F02=? AND T6025.F03=?");
		return select(getConnection(P2PConst.DB_USER), new ItemParser<UserZhEntity>() {
			UserZhEntity x = new UserZhEntity();

			@Override
			public UserZhEntity parse(ResultSet re) throws SQLException {
				while (re.next()) {
					x.bid = re.getInt(1);
					x.xlb_ky = re.getBigDecimal(2);
					x.xlb_dj = re.getBigDecimal(3);
					x.ywjc = re.getString(4);
					x.zwm = re.getString(5);
					x.tblj = re.getString(6);
				}
				return x;
			}
		}, sql.toString(), serviceResource.getSession().getAccountId(), bid);
	}

	@Override
	public int getBid(int scid) throws Throwable {
		if (scid <= 0) {
			return 0;
		}
		return selectInt(P2PConst.DB_USER, "SELECT F04 FROM T6015 WHERE F01=?", scid);
	}

	@Override
	public JlEntity[] searchWtjl(int scid) throws Throwable {
		StringBuffer sql = new StringBuffer("SELECT T6017.F09 sj,T6017.F07 zt,T6017.F04 jg,T6017.F05 sl,");
		sql.append(" 	T6017.F06 ycjsl,T6015.F05 ws,T6017.F01 id,");
		sql.append(" 	mr.F03 ywm_c,mr.F04 zwm_c, mc.F03 ywm_r,mc.F04 zwm_r,T6017.F02 scid");
		sql.append("  	FROM T6017 LEFT JOIN T6015 ON T6017.F02=T6015.F01");
		sql.append("  	LEFT JOIN T6013 mr ON mr.F01=T6015.F03 ");
		sql.append("  	LEFT JOIN T6013 mc ON mc.F01=T6015.F04 ");
		sql.append("  	WHERE 1=1");
		sql.append("  	AND T6017.F02=? AND T6017.F03=? AND T6017.F08=? ");
		sql.append(" ORDER BY T6017.F09 DESC");
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<JlEntity>() {
			ArrayList<JlEntity> list = new ArrayList<JlEntity>();

			@Override
			public JlEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					JlEntity x = new JlEntity();
					x.sj = re.getTimestamp(1);
					x.jyztStatus = EnumParser.parse(JyztStatus.class, re.getString(2));
					x.cjjg = re.getBigDecimal(3);
					x.cjsl = re.getBigDecimal(4);
					x.ycjsl = re.getBigDecimal(5);
					x.ws = re.getInt(6);
					x.wtid = re.getLong(7);
					x.ywm_m = re.getString(8);
					x.zwm_m = re.getString(9);
					x.ywm_s = re.getString(10);
					x.zwm_s = re.getString(11);
					x.scid = re.getLong(12);
					list.add(x);
				}
				return list == null ? null : list.toArray(new JlEntity[list.size()]);
			}
		}, sql.toString(), scid, serviceResource.getSession().getAccountId(), EntrustType.JYZ);
	}

	@Override
	public WdwtEntity[] searchWdwt(int scid) throws Throwable {
		StringBuffer sql = new StringBuffer("SELECT T6017.F09 sj,T6017.F07 zt,T6017.F04 jg,T6017.F05 sl,");
		sql.append(" 	T6017.F06 ycjsl,T6015.F05 ws,T6017.F01 id,T6017.F02 scid");
		sql.append("  	FROM T6017 LEFT JOIN T6015 ON T6017.F02=T6015.F01");
		sql.append("  	LEFT JOIN T6013 mr ON mr.F01=T6015.F03 ");
		sql.append("  	LEFT JOIN T6013 mc ON mc.F01=T6015.F04 ");
		sql.append("  	WHERE 1=1");
		sql.append("  	AND T6017.F02=? AND T6017.F03=? AND T6017.F08=? ");
		sql.append(" ORDER BY T6017.F09 DESC");
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<WdwtEntity>() {
			ArrayList<WdwtEntity> list = new ArrayList<WdwtEntity>();

			@Override
			public WdwtEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					WdwtEntity x = new WdwtEntity();
					x.sj = TimestampParser.format(re.getTimestamp(1));
					x.jyztStatus = EnumParser.parse(JyztStatus.class, re.getString(2)).getName();
					x.cjjg = Formater.formatAmount_(re.getBigDecimal(3), re.getInt(6));
					x.cjsl = Formater.formatAmount_(re.getBigDecimal(4), re.getInt(6));
					x.ycjsl = Formater.formatAmount_(re.getBigDecimal(5), re.getInt(6));
					x.ws = re.getInt(6);
					x.wtid = re.getLong(7);
					x.scid = re.getLong(8);
					x.ze = Formater.formatAmount_(
							(re.getBigDecimal(4).subtract(re.getBigDecimal(5))).multiply(re.getBigDecimal(3)), 3);
					if (EnumParser.parse(JyztStatus.class, re.getString(2)) == JyztStatus.MC) {
						x.ys = "sell";
					} else {
						x.ys = "buy";
					}
					list.add(x);
				}
				return list == null ? null : list.toArray(new WdwtEntity[list.size()]);
			}
		}, sql.toString(), scid, serviceResource.getSession().getAccountId(), EntrustType.JYZ);
	}

	@Override
	public XlbEntity[] getXlbList(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		StringBuffer sql = new StringBuffer("SELECT  ");
		sql.append(
				"  T6016.F03 zrsp,T6016.F04 dqj,T6016.F05 zgj,T6016.F06 zdj,T6016.F07 mc_yj,T6016.F08 mc_yj,T6016.F09 cjl,T6016.F10 cje,");
		sql.append("  sp.F03 ywm_c,sp.F04 zwm_c, m.F03 ywm_r,m.F04 zwm_r,sp.F05 tblj,T6015.F05 ws");
		sql.append("  FROM T6015  LEFT JOIN T6016 ON T6016.F02=T6015.F01");
		sql.append("  LEFT JOIN T6013 sp ON T6015.F04=sp.F01");
		sql.append("  LEFT JOIN T6013 m ON T6015.F03=m.F01 ");
		sql.append("  WHERE T6015.F01=?");
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<XlbEntity>() {
			ArrayList<XlbEntity> list = new ArrayList<XlbEntity>();

			@Override
			public XlbEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					XlbEntity x = new XlbEntity();
					x.spj = re.getBigDecimal(1);
					x.dqj = re.getBigDecimal(2);
					x.zgj = re.getBigDecimal(3);
					x.zdj = re.getBigDecimal(4);
					x.mr_yj = re.getBigDecimal(5);
					x.mc_yj = re.getBigDecimal(6);
					x.cjl = re.getBigDecimal(7);
					x.cje = re.getBigDecimal(8);
					x.ywm_s = re.getString(9);
					x.zwm_s = re.getString(10);
					x.ywm_m = re.getString(11);
					x.zwm_m = re.getString(12);
					x.tblj = re.getString(13);
					x.ws = re.getInt(14);
					list.add(x);
				}
				return list == null ? null : list.toArray(new XlbEntity[list.size()]);
			}
		}, sql.toString(), scid);
	}
	@Override
	public XlbEntity getB(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		StringBuffer sql = new StringBuffer("SELECT  ");
		sql.append(
				"  T6016.F03 zrsp,T6016.F04 dqj,T6016.F05 zgj,T6016.F06 zdj,T6016.F07 mc_yj,T6016.F08 mc_yj,T6016.F09 cjl,T6016.F10 cje,");
		sql.append("  sp.F03 ywm_c,sp.F04 zwm_c, m.F03 ywm_r,m.F04 zwm_r,sp.F05 tblj,T6015.F05 ws,");
		sql.append(
				"  T6015.F06 mr_sxfl, T6015.F07 mc_sxfl, T6015.F08 mr_min, T6015.F09 mr_max, T6015.F10 mc_min,T6015.F11 mc_max,");
		sql.append("  T6015.F01,sp.F22 tcrq, sp.F02 ywm,sp.F28,sp.F29,sp.F30,sp.F31,T6015.F15");
		sql.append("  FROM T6015  LEFT JOIN T6016 ON T6016.F02=T6015.F01");
		sql.append("  LEFT JOIN T6013 sp ON T6015.F04=sp.F01");
		sql.append("  LEFT JOIN T6013 m ON T6015.F03=m.F01 ");
		sql.append("  WHERE T6015.F01=?");
		return select(getConnection(P2PConst.DB_USER), new ItemParser<XlbEntity>() {
			XlbEntity x = new XlbEntity();

			@Override
			public XlbEntity parse(ResultSet re) throws SQLException {
				while (re.next()) {
					x.spj = re.getBigDecimal(1);
					x.dqj = re.getBigDecimal(2);
					x.zgj = re.getBigDecimal(3);
					x.zdj = re.getBigDecimal(4);
					x.mr_yj = re.getBigDecimal(5);
					x.mc_yj = re.getBigDecimal(6);
					x.cjl = re.getBigDecimal(7);
					x.cje = re.getBigDecimal(8);
					x.ywm_s = re.getString(9);
					x.zwm_s = re.getString(10);
					x.ywm_m = re.getString(11);
					x.zwm_m = re.getString(12);
					x.tblj = re.getString(13);
					x.ws = re.getInt(14);
					x.mr_sxfl = re.getBigDecimal(15);
					x.mc_sxfl = re.getBigDecimal(16);
					x.mr_min = re.getBigDecimal(17);
					x.mr_max = re.getBigDecimal(18);
					x.mc_min = re.getBigDecimal(19);
					x.mc_max = re.getBigDecimal(20);
					x.scid = re.getInt(21);
					x.tcrq = re.getTimestamp(22);
					x._ywm_s = re.getString(23);
					x.zwm_f = re.getString(24);
					x.desc = re.getString(25);
					x.descEn = re.getString(26);
					x.descTw = re.getString(27);
					x.slws=re.getInt(28);
				}
				return x;
			}
		}, sql.toString(), scid);
	}

	@Override
	public int tradingMr(int scid, BigDecimal price, BigDecimal num, String... parameter) throws Throwable {
		serviceResource.openTransactions();
		int coinId = 0;
		try {
			if (scid <= 0) {
				throw new ParameterException("err_1023");
			}
			if (price.compareTo(new BigDecimal(0)) <= 0 || price == null) {
				throw new ParameterException("err_1066");
			}
			if (num.compareTo(new BigDecimal(0)) <= 0 || num == null) {
				throw new ParameterException("err_1067");
			}
			/**
			 * 最后一个参数包含</br>
			 * 第一个交易密码</br>
			 * 第二个apikey</br>
			 * 正常只有一个，存在两个的时候一定是机器人跑的，所以机器人跑的一定要校验交易密码
			 */
			if (parameter.length >= 2 || getMmsr().equals(JymmType.MBJY.toString())) {
				if (StringHelper.isEmpty(parameter[0])) {
					throw new ParameterException("err_1016");
				}
				if (!Jymm(parameter)) {
					throw new ParameterException("err_1029");
				}
			}
			if (!sfsd(parameter)) {
				throw new ParameterException("err_1030");
			}
			int userid = 0;
			if (parameter.length >= 2) {
				userid = getUserId(parameter[1]);
			} else {
				userid = serviceResource.getSession().getAccountId();
			}
			if (userid <= 0) {
				throw new ParameterException("err_1021");
			}

			BigDecimal mr_min = new BigDecimal(0);// 买入最小交易价
			BigDecimal mr_max = new BigDecimal(0);// 买入最大交易价
			IsPass sfkqjy = null;// 是否开启交易
			IsPass sfxs = null;// 是否显示
			try (Connection connection = getConnection(P2PConst.DB_USER)) {
				try (PreparedStatement ps = connection
						.prepareStatement("SELECT F08,F09,F12,F13 FROM T6015 WHERE F01=?  ")) {// 锁市场表
					ps.setInt(1, scid);
					try (ResultSet re = ps.executeQuery()) {
						while (re.next()) {
							mr_min = re.getBigDecimal(1);
							mr_max = re.getBigDecimal(2);
							sfkqjy = EnumParser.parse(IsPass.class, re.getString(3));
							sfxs = EnumParser.parse(IsPass.class, re.getString(4));
						}
					}
				}
			}
			if (sfkqjy == null || sfkqjy == IsPass.F) {
				throw new ParameterException("err_1068");
			}
			if (sfxs == null || sfxs == IsPass.F) {
				throw new ParameterException("err_1069");
			}
			BigDecimal mr_cny = num.multiply(price).setScale(8, BigDecimal.ROUND_HALF_DOWN);// 买入金额
			if (mr_cny.compareTo(mr_min) < 0) {
				throw new ParameterException("委托金额不能小于" + mr_min + "元");
			}
			if (mr_cny.compareTo(mr_max) > 0) {
				throw new ParameterException("委托金额不能大于" + mr_max + "元");
			}
			Market market = getMarkeyById(scid);
			
			BigDecimal zh_ky_cny;	
			
			//买方为人民币(这里暂时写死人民币的ID为16了，以后想到好的方式再优化此处)
			if(market.getBuyCoinID()==0) {
				zh_ky_cny=selectBigDecimal(P2PConst.DB_USER, "SELECT F04 FROM T6023 WHERE F01=? for update", userid);// 锁用户表
				if (mr_cny.compareTo(zh_ky_cny) > 0) {
					throw new ParameterException("err_1042");
				}
				execute(getConnection(P2PConst.DB_USER), "UPDATE T6023 SET F03=F03+?,F04=F04-? WHERE F01=?", mr_cny, mr_cny,userid);
			}else {//币币交易
				zh_ky_cny=selectBigDecimal(P2PConst.DB_USER, "SELECT F04 FROM T6025 WHERE F01=?  for update", userid);// 锁用户表
				if (mr_cny.compareTo(zh_ky_cny) > 0) {
					throw new ParameterException("err_1042");
				}
				execute(getConnection(P2PConst.DB_USER), "UPDATE T6025 SET F04=F04-?,F05=F05+? WHERE F02=? AND F03=?", mr_cny, mr_cny,userid,market.getBuyCoinID());
			}

			coinId = insert(getConnection(P2PConst.DB_USER),
					"INSERT INTO T6017 SET F02=?,F03=?,F04=?,F05=?,F06=0,F07=?,F08=?,F09=CURRENT_TIMESTAMP(),F10=?", scid,
					userid, price, num, JyztStatus.MR, EntrustType.JYZ,"F");
			
			
		} catch (Throwable e) {
			serviceResource.rollback();
			e.printStackTrace();
			throw new LogicalException(e.getMessage());
		}
		return coinId;
	}
	
	/*
	 * 通过市场ID，获取记录
	 * */
	private Market getMarkeyById(int markId) throws ResourceNotFoundException, SQLException {
		String sql  = "SELECT * FROM "+P2PConst.DB_USER+".T6015 WHERE F01=?";
		return this.select(getConnection(P2PConst.DB_USER), new ItemParser<Market>() {
			Market m = new Market();
			@Override
			public Market parse(ResultSet rs) throws SQLException {
				while (rs.next()) {
					m.setMarkID(rs.getInt(1));
					m.setPartitionID(rs.getInt(2));
					m.setBuyCoinID(rs.getInt(3));
					m.setSellCoinID(rs.getInt(4));
					m.setDecimalDigit(rs.getInt(5));
					m.setBuyFee(rs.getDouble(6));
					m.setSellFee(rs.getDouble(7));
					m.setBuyMinPrice(rs.getDouble(8));
					m.setBuyMaxPrice(rs.getDouble(9));
					m.setSellMinPrice(rs.getDouble(10));
					m.setSellMaxPrice(rs.getDouble(11));
					m.setOpen(null != rs.getString(12) ? rs.getString(12).equalsIgnoreCase("S") : false);
					m.setShow(null != rs.getString(13) ? rs.getString(13).equalsIgnoreCase("S") : false);
					m.setTime(rs.getTimestamp(14));					
				}
				return m;
			}
		}, sql, markId);
	} 

	@Override
	public int tradingMc(int scid, BigDecimal price, BigDecimal num, String... parameter) throws Throwable {
		serviceResource.openTransactions();
		int coinId = 0;
		try {
			if (scid <= 0) {
				throw new ParameterException("err_1023");
			}
			if (price.compareTo(new BigDecimal(0)) <= 0 || price == null) {
				throw new ParameterException("err_1066");
			}
			if (num.compareTo(new BigDecimal(0)) <= 0 || num == null) {
				throw new ParameterException("err_1067");
			}

			/**
			 * 最后一个参数包含</br>
			 * 第一个交易密码</br>
			 * 第二个apikey</br>
			 * 正常只有一个，存在两个的时候一定是机器人跑的，所以机器人跑的一定要校验交易密码
			 */
			if (parameter.length >= 2 || getMmsr().equals(JymmType.MBJY.toString())) {
				if (StringHelper.isEmpty(parameter[0])) {
					throw new ParameterException("err_1016");
				}
				if (!Jymm(parameter)) {
					throw new ParameterException("err_1029");
				}
			}

			if (!sfsd(parameter)) {
				throw new ParameterException("err_1030");
			}
			int userid = 0;
			if (parameter.length >= 2) {
				userid = getUserId(parameter[1]);
			} else {
				userid = serviceResource.getSession().getAccountId();
			}
			if (userid <= 0) {
				throw new ParameterException("err_1021");
			}
			int mc_bid = 0;// 卖出币种
			BigDecimal mc_min = new BigDecimal(0);// 买出最小交易价
			BigDecimal mc_max = new BigDecimal(0);// 买出最大交易价
			IsPass sfkqjy = null;// 是否开启交易
			IsPass sfxs = null;// 是否显示
			try (Connection connection = getConnection(P2PConst.DB_USER)) {
				try (PreparedStatement ps = connection
						.prepareStatement("SELECT F10,F11,F12,F13,F04 FROM T6015 WHERE F01=? ")) {// 锁市场表
					ps.setInt(1, scid);
					try (ResultSet re = ps.executeQuery()) {
						while (re.next()) {
							mc_min = re.getBigDecimal(1);
							mc_max = re.getBigDecimal(2);
							sfkqjy = EnumParser.parse(IsPass.class, re.getString(3));
							sfxs = EnumParser.parse(IsPass.class, re.getString(4));
							mc_bid = re.getInt(5);
						}
					}
				}
			}
			if (sfkqjy == null || sfkqjy == IsPass.F) {
				throw new ParameterException("err_1068");
			}
			if (sfxs == null || sfxs == IsPass.F) {
				throw new ParameterException("err_1069");
			}
			BigDecimal mc_cny = num.multiply(price).setScale(8, BigDecimal.ROUND_HALF_DOWN);// 买入金额
			if (mc_cny.compareTo(mc_min) < 0) {
				throw new ParameterException("委托金额不能小于" + mc_min + "元");
			}
			if (mc_cny.compareTo(mc_max) > 0) {
				throw new ParameterException("委托金额不能大于" + mc_max + "元");
			}
			if (mc_bid <= 0) {
				throw new ParameterException("err_1025");
			}
			int T6025_F01 = selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6025 WHERE F02=? AND F03= ?", userid, mc_bid);
			if (T6025_F01 <= 0) {
				throw new ParameterException("err_1025");
			}
			selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6025 WHERE F01=? FOR UPDATE", T6025_F01);

			BigDecimal xlb_ky_cny = selectBigDecimal(P2PConst.DB_USER, "SELECT F04 FROM T6025 WHERE F02=? AND F03=? ",
					userid, mc_bid);// 用户账户可用虚拟币
			if (num.compareTo(xlb_ky_cny) > 0) {
				throw new ParameterException("err_1070");
			}
			execute(getConnection(P2PConst.DB_USER), "UPDATE T6025 SET F04=F04-?,F05=F05+? WHERE  F02=? AND F03=? ",
					num, num, userid, mc_bid);
			coinId = insert(getConnection(P2PConst.DB_USER),
					"INSERT INTO T6017 SET F02=?,F03=?,F04=?,F05=?,F06=0,F07=?,F08=?,F09=CURRENT_TIMESTAMP(),F10=?", scid,
					userid, price, num, JyztStatus.MC, EntrustType.JYZ,"F");
		} catch (Throwable e) {
			serviceResource.rollback();
			e.printStackTrace();
			throw new LogicalException(e.getMessage());
		}
		return coinId;
	}

	public boolean Jymm(String... parameter) throws Throwable {

		int userid = 0;
		if (parameter.length >= 2) {
			userid = getUserId(parameter[1]);
		} else {
			userid = serviceResource.getSession().getAccountId();
		}
		if (userid <= 0) {
			throw new ParameterException("err_1021");
		}
		String _ymm = selectString(P2PConst.DB_USER, "SELECT F11 FROM T6011 WHERE F01=?", userid);
		if (parameter.length >= 2) {
			if (!parameter[0].equals(_ymm)) {
				return false;
			}
		} else {
			String md5password = MD5.getMd5Value(parameter[0]);
			if (md5password.equals(_ymm)) {
				execute(getConnection(FrontConst.DB_USER), "UPDATE T6011 SET F11=? WHERE F01=?",
						UnixCrypt.crypt(parameter[0], DigestUtils.sha256Hex(parameter[0])),
						serviceResource.getSession().getAccountId());
			} else {
				if (!UnixCrypt.crypt(parameter[0], DigestUtils.sha256Hex(parameter[0])).equals(_ymm)) {
					return false;
				}
			}
		}

		return true;
	}

	private boolean sfsd(String... parameter) throws Throwable {
		int userid = 0;
		if (parameter.length >= 2) {
			userid = getUserId(parameter[1]);
		} else {
			userid = serviceResource.getSession().getAccountId();
		}
		if (userid <= 0) {
			throw new ParameterException("err_1021");
		}
		String sfsd = selectString(P2PConst.DB_USER, "SELECT F06 FROM T6011 WHERE F01=?", userid);
		if (String.valueOf(IsPass.S).equals(sfsd)) {
			return false;
		}
		return true;
	}

	@Override
	public HqEntity getHq(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		StringBuffer sql = new StringBuffer("SELECT  ");
		sql.append(
				"  T6015.F05 ws,T6016.F03 zrsp,T6016.F04 dqj,T6016.F05 zgj,T6016.F06 zdj,T6016.F07 mc_yj,T6016.F08 mc_yj,T6016.F09 cjl,T6016.F10 cje,");
		sql.append("  sp.F03 ywm_c,sp.F04 zwm_c, m.F03 ywm_r,m.F04 zwm_r,sp.F05 tblj,");
		sql.append("  T6015.F01 scid");
		sql.append("  FROM T6015  LEFT JOIN T6016 ON T6016.F02=T6015.F01");
		sql.append("  LEFT JOIN T6013 sp ON T6015.F04=sp.F01");
		sql.append("  LEFT JOIN T6013 m ON T6015.F03=m.F01 ");
		sql.append("  WHERE T6015.F01=?");
		return select(getConnection(P2PConst.DB_USER), new ItemParser<HqEntity>() {
			HqEntity x = new HqEntity();

			@Override
			public HqEntity parse(ResultSet re) throws SQLException {
				while (re.next()) {
					x.ws = re.getInt(1);
					x.spj = Formater.formatAmount_(re.getBigDecimal(2), x.ws);
					x.dqj = Formater.formatAmount_(re.getBigDecimal(3), x.ws);
					x.zgj = Formater.formatAmount_(re.getBigDecimal(4), x.ws);
					x.zdj = Formater.formatAmount_(re.getBigDecimal(5), x.ws);
					x.mr_yj = Formater.formatAmount_(re.getBigDecimal(6), x.ws);
					x.mc_yj = Formater.formatAmount_(re.getBigDecimal(7), x.ws);
					x.cjl = Formater.formatAmount(re.getBigDecimal(8));
//					if (re.getBigDecimal(8).compareTo(new BigDecimal(10000)) > 0) {
//						x.cjl = re.getBigDecimal(8).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP) + "万";
//					}
					x.cje = Formater.formatAmount_(re.getBigDecimal(9), x.ws);
					x.ywm_s = re.getString(10);
					x.zwm_s = re.getString(11);
					x.ywm_m = re.getString(12);
					x.zwm_m = re.getString(13);
					x.tblj = re.getString(14);
					x.scid = re.getInt(15);
					if (re.getBigDecimal(3).compareTo(new BigDecimal(0)) != 0) {
						if(re.getBigDecimal(2).compareTo(new BigDecimal(0)) == 0) {
							x.rzd = "100";
						}else {
							x.rzd = Formater.formatAmount((re.getBigDecimal(3).subtract(re.getBigDecimal(2)))
									.divide(re.getBigDecimal(2), 4, BigDecimal.ROUND_HALF_UP)
									.multiply(new BigDecimal(100)));
						}
					} else {
						x.rzd = "0";
					}
				}
				return x;
			}
		}, sql.toString(), scid);
	}

	@Override
	public List<Map<String, Object>> getMarket(String name) throws Throwable {
		StringBuffer queryMarketSql = new StringBuffer("SELECT MARKETID,MARKET_NAME FROM (SELECT F01 MARKETID,");
		queryMarketSql.append("CONCAT((SELECT F03 FROM T6013 B WHERE B.F01 = A.F04),");
		queryMarketSql.append("'_',(SELECT F03 FROM T6013 B WHERE B.F01 = A.F03))");
		queryMarketSql.append("  MARKET_NAME FROM T6015 A) B");
		Object[] parameters;
		if (name != null) {
			parameters = new Object[1];
			parameters[0] = name;
			queryMarketSql.append("  WHERE B.MARKET_NAME = ? ");
		} else {
			parameters = new Object[0];
		}
		List<Map<String, Object>> marketMap = select(getConnection(P2PConst.DB_USER),
				new ItemParser<List<Map<String, Object>>>() {

					@Override
					public List<Map<String, Object>> parse(ResultSet paramResultSet) throws SQLException {
						List<Map<String, Object>> listMarkMap = new ArrayList<>();
						while (paramResultSet.next()) {
							Map<String, Object> marketMap = new HashMap<>();
							marketMap.put("marketId", paramResultSet.getLong(1));
							marketMap.put("marketName", paramResultSet.getString(2).toLowerCase());
							listMarkMap.add(marketMap);
						}
						return listMarkMap;
					}

				}, queryMarketSql.toString(), parameters);
		return marketMap;
	}

	@Override
	public Map<String, Object> getTrades(String name) throws Throwable {
		List<Map<String, Object>> listMarkMap = getMarket(name);
		Map<String, Object> result = new HashMap<>();
		if (listMarkMap != null && listMarkMap.size() > 0) {
			StringBuffer sb = new StringBuffer(" SELECT DATE_FORMAT(f11,'%m-%d %H:%i:%s')  addtime,  ");
			sb.append(" IF (f10 = 'MR', 'buy', 'sell') type, f05 price, F06 num, F07 mun FROM t6018 ");
			sb.append(" WHERE F02 = ? LIMIT 50 ");
			for (Map<String, Object> m : listMarkMap) {
				List<Map<String, Object>> data = select(getConnection(P2PConst.DB_USER),
						new ItemParser<List<Map<String, Object>>>() {
							@Override
							public List<Map<String, Object>> parse(ResultSet paramResultSet) throws SQLException {
								List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
								while (paramResultSet.next()) {
									Map<String, Object> coinMap = new HashMap<>();
									coinMap.put("addtime", paramResultSet.getString(1));
									coinMap.put("type", paramResultSet.getString(2));
									coinMap.put("price", paramResultSet.getBigDecimal(3));
									coinMap.put("num", paramResultSet.getBigDecimal(4));
									coinMap.put("mun", paramResultSet.getBigDecimal(5));
									list.add(coinMap);
								}
								return list;
							}

						}, sb.toString(), m.get("marketId"));

				result.put(m.get("marketName").toString(), data);
			}
		}
		return result;
	}

	//这个接口没有使用
	@Override
	public Map<String, Object> getDepth(String name) throws Throwable {
		List<Map<String, Object>> listMarkMap = getMarket(name);
		Map<String, Object> result = new HashMap<>();
		if (listMarkMap != null && listMarkMap.size() > 0) {
			StringBuffer sb = new StringBuffer(" SELECT F02,F03 FROM t6016_1 ");
			sb.append(" WHERE F02 = ? AND F07=1 AND F05='MR' limit 15");
			StringBuffer sb1 = new StringBuffer(" SELECT F02,F03 FROM t6016_1 ");
			sb1.append(" WHERE F02 = ? AND F07=1 AND F05='MC' limit 15");
			for (Map<String, Object> m : listMarkMap) {
				Map<String, Object> data = new HashMap<>();
				List<List<BigDecimal>> listAll = select(getConnection(P2PConst.DB_USER),
						new ItemParser<List<List<BigDecimal>>>() {
							@Override
							public List<List<BigDecimal>> parse(ResultSet paramResultSet) throws SQLException {
								List<List<BigDecimal>> listAll = new ArrayList<List<BigDecimal>>();
								while (paramResultSet.next()) {
									List<BigDecimal> list = new ArrayList<BigDecimal>();
									list.add(paramResultSet.getBigDecimal(1));
									list.add(paramResultSet.getBigDecimal(2));
									listAll.add(list);
								}

								return listAll;
							}

						}, sb.toString(), m.get("marketId"));
				data.put("buy", listAll);
				List<List<BigDecimal>> listAllSell = select(getConnection(P2PConst.DB_USER),
						new ItemParser<List<List<BigDecimal>>>() {
							@Override
							public List<List<BigDecimal>> parse(ResultSet paramResultSet) throws SQLException {
								List<List<BigDecimal>> listAll = new ArrayList<List<BigDecimal>>();
								while (paramResultSet.next()) {
									List<BigDecimal> list = new ArrayList<BigDecimal>();
									list.add(paramResultSet.getBigDecimal(1));
									list.add(paramResultSet.getBigDecimal(2));
									listAll.add(list);
								}

								return listAll;
							}

						}, sb1.toString(), m.get("marketId"));
				data.put("sell", listAllSell);
				result.put(m.get("marketName").toString(), data);
			}

		}
		return result;
	}

	@Override
	public Map<String, Object> getAllCoin(String name) throws Throwable {
		List<Map<String, Object>> listMarkMap = getMarket(name);
		Map<String, Object> result = new HashMap<>();
		if (listMarkMap != null && listMarkMap.size() > 0) {
			StringBuffer virtualCoinSql = new StringBuffer("SELECT F04 last,F07 buy, F08 sell,F10 volumeCny,");
			virtualCoinSql.append("F09 volume,F06 min,F05 max,F03 FROM T6016 WHERE F02 = ?");
			for (Map<String, Object> m : listMarkMap) {
				Map<String, Object> coinMap = select(getConnection(P2PConst.DB_USER),
						new ItemParser<Map<String, Object>>() {
							@Override
							public Map<String, Object> parse(ResultSet paramResultSet) throws SQLException {
								Map<String, Object> coinMap = new HashMap<>();
								if (paramResultSet.next()) {
									
									BigDecimal currentCoin = paramResultSet.getBigDecimal(1);
									coinMap.put("last", paramResultSet.getBigDecimal(1));
									coinMap.put("buy", paramResultSet.getBigDecimal(2));
									coinMap.put("sell", paramResultSet.getBigDecimal(3));
									coinMap.put("volumeCny", paramResultSet.getBigDecimal(4));
									coinMap.put("volume", paramResultSet.getBigDecimal(5));
									coinMap.put("min", paramResultSet.getBigDecimal(6));
									coinMap.put("max", paramResultSet.getBigDecimal(7));
									BigDecimal yesterday = paramResultSet.getBigDecimal(8);
									if (currentCoin.compareTo(new BigDecimal(0)) <= 0) {
										coinMap.put("change", 0);
									} else {
										coinMap.put("change", currentCoin.subtract(yesterday).divide(currentCoin, 4,
												BigDecimal.ROUND_HALF_UP));
									}
									coinMap.put("img", "");
								}
								return coinMap;
							}

						}, virtualCoinSql.toString(), m.get("marketId"));

				result.put(m.get("marketName").toString(), coinMap);
			}
		}

		return result;
	}

	@Override
	public WtEntity[] getWtMr(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<WtEntity>() {
			ArrayList<WtEntity> list = new ArrayList<WtEntity>();

			@Override
			public WtEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					WtEntity x = new WtEntity();
					x.scid = re.getInt(1);
					x.ws = getXsws(x.scid);
					x.jg = Formater.formatAmount_(re.getBigDecimal(2), x.ws);
					x.sl = Formater.formatAmount_(re.getBigDecimal(3), x.ws);
					x.ze = Formater.formatAmount(re.getBigDecimal(4));
					list.add(x);
				}
				return list == null ? null : list.toArray(new WtEntity[list.size()]);
			}
		}, "SELECT F01,F02,F03,F04 FROM t6016_1 WHERE F01=? AND F05=? AND F07 =1 ORDER BY F02 DESC LIMIT 15", scid,
				JyztStatus.MR);
	}

	private int getXsws(int scid) throws SQLException {
		return selectInt(P2PConst.DB_USER, "SELECT F05 FROM T6015 WHERE F01=?", scid);
	}

	@Override
	public WtEntity[] getWtMc(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<WtEntity>() {
			ArrayList<WtEntity> list = new ArrayList<WtEntity>();

			@Override
			public WtEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					WtEntity x = new WtEntity();
					x.scid = re.getInt(1);
					x.ws = getXsws(x.scid);
					x.jg = Formater.formatAmount_(re.getBigDecimal(2), x.ws);
					x.sl = Formater.formatAmount_(re.getBigDecimal(3), x.ws);
					x.ze = Formater.formatAmount(re.getBigDecimal(4));
					list.add(x);
				}
				return list == null ? null : list.toArray(new WtEntity[list.size()]);
			}
		}, "SELECT F01,F02,F03,F04 FROM t6016_1 WHERE F01=? AND F05=? AND F07=1 ORDER BY F02 ASC LIMIT 15", scid,
				JyztStatus.MC);
	}

	@Override
	public WtEntity[] getCjjl(int scid, int i) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		if (i == 1) {
			int count = selectInt(P2PConst.DB_USER,
					"SELECT COUNT(F01) FROM T6018 WHERE F02=? AND DATE_SUB(NOW(),interval 5 SECOND)<=F11 ORDER BY F11 DESC",
					scid);
			if (count <= 50) {
				i = 0;
			}
		}
		StringBuffer s = new StringBuffer();
		if (i == 1) {
			s.append(
					"SELECT F02,F05,F06,F07,F10,F11 FROM T6018 WHERE F02=? AND DATE_SUB(NOW(),interval 5 SECOND)<=F11 ORDER BY F11 DESC ");
		} else {
			s.append(" SELECT F02,F05,F06,F07,F10,F11 FROM T6018 WHERE F02=? ORDER BY F11 DESC LIMIT 50 ");
		}
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<WtEntity>() {
			ArrayList<WtEntity> list = new ArrayList<WtEntity>();

			@Override
			public WtEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					WtEntity x = new WtEntity();
					x.scid = re.getInt(1);
					x.ws = getXsws(x.scid);
					x.jg = Formater.formatAmount_(re.getBigDecimal(2), x.ws);
					x.sl = Formater.formatAmount_(re.getBigDecimal(3), x.ws);
					x.ze = Formater.formatAmount_(re.getBigDecimal(4), 3);
					x.type = EnumParser.parse(JyztStatus.class, re.getString(5)).getName();
					x.sj = TimestampParser.format(re.getTimestamp(6));
					x.cs = "sell";
					if (EnumParser.parse(JyztStatus.class, re.getString(5)) == JyztStatus.MR) {
						x.cs = "buy";
					}
					list.add(x);
				}
				return list == null ? null : list.toArray(new WtEntity[list.size()]);
			}
		}, s.toString(), scid);
	}

	@Override
	public String getMmsr() throws Throwable {
		return selectString(P2PConst.DB_USER, "SELECT F12 FROM T6011 WHERE F01=?",
				serviceResource.getSession().getAccountId());
	}

	@Override
	public HqEntity[] hqList() throws Throwable {
		final FileStore fileStore = serviceResource.getResource(FileStore.class);
		StringBuffer sql = new StringBuffer("SELECT  ");
		sql.append(
				" T6015.F05 ws,T6016.F03 zrsp,T6016.F04 dqj,T6016.F05 zgj,T6016.F06 zdj,T6016.F07 mc_yj,T6016.F08 mc_yj,T6016.F09 cjl,T6016.F10 cje,");
		sql.append("  sp.F02 sell_shortName, sp.F03 sell_fullName, sp.F04 sell_cnName, m.F02 buy_shortName, m.F03 buy_fullName, m.F04 buy_cnName,sp.F05 tblj,");
		sql.append("  T6015.F01 scid,sp.F28 zwm_f,T6015.F12 kf");
		sql.append("  FROM T6015  LEFT JOIN T6016 ON T6016.F02=T6015.F01");
		sql.append("  LEFT JOIN T6013 sp ON T6015.F04=sp.F01");
		sql.append("  LEFT JOIN T6013 m ON T6015.F03=m.F01 ");
		sql.append("  WHERE T6015.F13=? ORDER BY T6015.F16 ASC");
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<HqEntity>() {
			ArrayList<HqEntity> list = new ArrayList<HqEntity>();

			@Override
			public HqEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					HqEntity x = new HqEntity();
					x.ws = re.getInt(1);
					x.spj = Formater.formatAmount_(re.getBigDecimal(2), x.ws);
					x.dqj = Formater.formatAmount_(re.getBigDecimal(3), x.ws);
					x.zgj = Formater.formatAmount_(re.getBigDecimal(4), x.ws);
					x.zdj = Formater.formatAmount_(re.getBigDecimal(5), x.ws);
					x.mr_yj = Formater.formatAmount_(re.getBigDecimal(6), x.ws);
					x.mc_yj = Formater.formatAmount_(re.getBigDecimal(7), x.ws);
					x.cjl = Formater.formatAmount(re.getBigDecimal(8));
//					if (re.getBigDecimal(8).compareTo(new BigDecimal(10000)) > 0) {
//						x.cjl = Formater.formatAmount(
//								re.getBigDecimal(8).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP)) + "万";
//					}
					x.cje = Formater.formatAmount(re.getBigDecimal(9));
//					if (re.getBigDecimal(9).compareTo(new BigDecimal(10000)) > 0) {
//						x.cje = Formater.formatAmount(
//								re.getBigDecimal(9).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP)) + "万";
//					}
					x.sell_shortName = re.getString(10);
					x.sell_fullName = re.getString(11);
					x.sell_cnName = re.getString(12);
					x.buy_shortName = re.getString(13);
					x.buy_fullName = re.getString(14);
					x.buy_cnName = re.getString(15);
					
					if(null!=re.getString(16))
					x.tblj = fileStore.getURL(re.getString(16));
					x.scid = re.getInt(17);
					x.zwm_f = re.getString(18);
					x.is_trade = EnumParser.parse(IsPass.class, re.getString(19));
					if (re.getBigDecimal(3).compareTo(new BigDecimal(0)) != 0) {
						if(re.getBigDecimal(2).compareTo(new BigDecimal(0)) == 0) {
							x.rzd = "100";
						}else {
							x.rzd = Formater.formatAmount((re.getBigDecimal(3).subtract(re.getBigDecimal(2)))
									.divide(re.getBigDecimal(2), 4, BigDecimal.ROUND_HALF_UP)
									.multiply(new BigDecimal(100)));
						}
					} else {
						x.rzd = "0";
					}
					list.add(x);
				}
				return list == null ? null : list.toArray(new HqEntity[list.size()]);
			}
		}, sql.toString(), IsPass.S);
	}

//	@Override
//	public HqEntity[] hqList() throws Throwable {
//		final FileStore fileStore = serviceResource.getResource(FileStore.class);
//		StringBuffer sql = new StringBuffer("SELECT  ");
//		sql.append(
//				"  T6015.F05 ws,T6016.F03 zrsp,T6016.F04 dqj,T6016.F05 zgj,T6016.F06 zdj,T6016.F07 mc_yj,T6016.F08 mc_yj,T6016.F09 cjl,T6016.F10 cje,");
//		sql.append("  sp.F03 ywm_c,sp.F04 zwm_c, m.F03 ywm_r,m.F04 zwm_r,sp.F05 tblj,");
//		sql.append("  T6015.F01 scid,sp.F28 zwm_f");
//		sql.append("  FROM T6015  LEFT JOIN T6016 ON T6016.F02=T6015.F01");
//		sql.append("  LEFT JOIN T6013 sp ON T6015.F04=sp.F01");
//		sql.append("  LEFT JOIN T6013 m ON T6015.F03=m.F01 ");
//		sql.append("  WHERE T6015.F13=? ORDER BY T6015.F01 ASC");
//		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<HqEntity>() {
//			ArrayList<HqEntity> list = new ArrayList<HqEntity>();
//
//			@Override
//			public HqEntity[] parse(ResultSet re) throws SQLException {
//				while (re.next()) {
//					HqEntity x = new HqEntity();
//					x.ws = re.getInt(1);
//					x.spj = Formater.formatAmount_(re.getBigDecimal(2), x.ws);
//					x.dqj = Formater.formatAmount_(re.getBigDecimal(3), x.ws);
//					x.zgj = Formater.formatAmount_(re.getBigDecimal(4), x.ws);
//					x.zdj = Formater.formatAmount_(re.getBigDecimal(5), x.ws);
//					x.mr_yj = Formater.formatAmount_(re.getBigDecimal(6), x.ws);
//					x.mc_yj = Formater.formatAmount_(re.getBigDecimal(7), x.ws);
//					x.cjl = Formater.formatAmount(re.getBigDecimal(8));
//					if (re.getBigDecimal(8).compareTo(new BigDecimal(10000)) > 0) {
//						x.cjl = Formater.formatAmount(
//								re.getBigDecimal(8).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP)) + "万";
//					}
//					x.cje = Formater.formatAmount(re.getBigDecimal(9));
//					if (re.getBigDecimal(9).compareTo(new BigDecimal(10000)) > 0) {
//						x.cje = Formater.formatAmount(
//								re.getBigDecimal(9).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP)) + "万";
//					}
//					x.ywm_s = re.getString(10);
//					x.zwm_s = re.getString(11);
//					x.ywm_m = re.getString(12);
//					x.zwm_m = re.getString(13);
//					if(null!=re.getString(14))
//					x.tblj = fileStore.getURL(re.getString(14));
//					x.scid = re.getInt(15);
//					x.zwm_f = re.getString(16);
//					if (re.getBigDecimal(3).compareTo(new BigDecimal(0)) != 0) {
//						x.rzd = Formater.formatAmount((re.getBigDecimal(3).subtract(re.getBigDecimal(2)))
//								.divide(re.getBigDecimal(3), 4, BigDecimal.ROUND_HALF_UP)
//								.multiply(new BigDecimal(100)));
//					} else {
//						x.rzd = "0";
//					}
//					list.add(x);
//				}
//				return list == null ? null : list.toArray(new HqEntity[list.size()]);
//			}
//		}, sql.toString(), IsPass.S);
//	}

	@Override
	public String getKline(long market, long time) throws Throwable {
		long minutm = time / 60;
		String table_name = "";
		if (minutm >= 60 && minutm < 360) {
			table_name = P2PConst.DB_USER+".t6019_market_n";
		} else if (minutm >= 360) {
			table_name = P2PConst.DB_USER+".t6019_market_m";
		} else {
			table_name = String.format(P2PConst.DB_USER+".t6019_%d%s%d", market, '_', time);
		}

		StringBuffer sql = new StringBuffer("SELECT F10 FROM");
		sql.append("  " + table_name);
		sql.append(" where F12=? AND F11=? order by F08 desc ");
		sql.append(" LIMIT 1000");
		Object[] parameters = new Object[2];
		parameters[0] = market;
		parameters[1] = time;
		StringBuilder resultString = new StringBuilder("[");
		try (PreparedStatement pstmt = getConnection(P2PConst.DB_USER).prepareStatement(sql.toString());) {
			serviceResource.setParameters(pstmt, parameters);
			try (ResultSet resultSet = pstmt .executeQuery();) {
				while (resultSet.next()) {
					resultString.insert(1, resultSet.getString(1) + ",");
					// resultString.append(resultSet.getString(1));
					// resultString.append(",");
				}

			}
		}

		String s = resultString.toString();
		if (s.length() > 2)
			s = s.substring(0, s.length() - 1);
		s += ("]");
		return s;
	}

	@Override
	public String getKlineNew(long market, long since) throws Throwable {
		StringBuilder sb = new StringBuilder(" select F01,UNIX_TIMESTAMP(F11),F05,F06 from t6018 WHERE F02=? ");
		List<KlineEntityNew> list = new ArrayList<>();
		if (since <= 0) {
			sb.append(" order by f01 desc limit 1 ");
			Object[] parameters = new Object[1];
			parameters[0] = market;

			try (PreparedStatement pstmt = getConnection(P2PConst.DB_USER).prepareStatement(sb.toString());) {
				serviceResource.setParameters(pstmt, parameters);
				try (ResultSet resultSet = pstmt.executeQuery();) {
					while (resultSet.next()) {
						KlineEntityNew k = new KlineEntityNew();
						k.tid = resultSet.getLong(1) + "";
						k.date = resultSet.getLong(2) + "";
						k.price = resultSet.getBigDecimal(3).toString();
						k.amount = resultSet.getBigDecimal(4).toString();
						list.add(k);
					}
				}
			}
		} else {
			sb.append(" AND f01 > ? ");
			Object[] parameters = new Object[2];
			parameters[0] = market;
			parameters[1] = since;
			try (PreparedStatement pstmt = getConnection(P2PConst.DB_USER).prepareStatement(sb.toString());) {
				serviceResource.setParameters(pstmt, parameters);
				try (ResultSet resultSet = pstmt.executeQuery();) {
					while (resultSet.next()) {
						KlineEntityNew k = new KlineEntityNew();
						k.tid = resultSet.getLong(1) + "";
						k.date = resultSet.getLong(2) + "";
						k.price = resultSet.getBigDecimal(3).toString();
						k.amount = resultSet.getBigDecimal(4).toString();
						list.add(k);
					}
				}
			}
		}

		return JsonUtil.GsonString(list);
	}

	@Override
	public XxcsEntity[] cyljSearch(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("市场不存在。");
		}
		int bid = getBid(scid);
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<XxcsEntity>() {
			ArrayList<XxcsEntity> list = new ArrayList<XxcsEntity>();

			@Override
			public XxcsEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					XxcsEntity x = new XxcsEntity();
					x.id = re.getInt(1);
					x.bid = re.getInt(2);
					x.mc = re.getString(3);
					x.dz = re.getString(4);
					x.sfxs = EnumParser.parse(IsPass.class, re.getString(5));
					x.px = re.getInt(6);
					x.linkNameOrParamEn = re.getString(7);
					x.linkNameOrParamTw = re.getString(8);
					list.add(x);
				}
				return list == null ? null : list.toArray(new XxcsEntity[list.size()]);
			}
		}, "SELECT F01,F02,F03,F04,F05,F06,F07,F08 FROM  T6013_2 WHERE F02=? AND F05=? ORDER BY F06 DESC", bid, IsPass.S);
	}

	@Override
	public Map<String, Object> getUserCoin(String apikey) throws Throwable {
		int userId = getUserId(apikey);
		Map<String, Object> result = new HashMap<>();
		if (userId > 0) {
			List<Map<String, Object>> listMarkMap = getMarket(null);
			Map<String, Object> coinList = new HashMap<>();
			if (listMarkMap != null && listMarkMap.size() > 0) {
				for (Map<String, Object> m : listMarkMap) {
					StringBuffer sb = new StringBuffer("");
					sb.append("select b.F02 name,b.F05 img,b.F04 title,a.F04 xnb,a.F05 xnbd,(a.F04+a.F05) xnbz ");
					sb.append(" ,c.F04 jia,(a.F04+a.F05)/c.F04 zhehe FROM t6025 a ");
					sb.append(" LEFT JOIN t6015 e on a.F03 = e.F04 ");
					sb.append(" LEFT JOIN t6013 b on b.F01 = e.F04 ");
					sb.append(" LEFT JOIN t6016 c on c.F02 = e.F01 ");
					sb.append(" WHERE a.F02=? AND  e.F01 = ?  ");

					Map<String, Object> coinMap = select(getConnection(P2PConst.DB_USER),
							new ItemParser<Map<String, Object>>() {
								@Override
								public Map<String, Object> parse(ResultSet paramResultSet) throws SQLException {
									Map<String, Object> map = new HashMap<>();
									if (paramResultSet.next()) {
										Map<String, Object> coinMap = new HashMap<>();
										String name = paramResultSet.getString(1);
										coinMap.put("name", name);
										coinMap.put("img", paramResultSet.getString(2));
										coinMap.put("title", paramResultSet.getString(3));
										coinMap.put("xnb", paramResultSet.getBigDecimal(4));
										coinMap.put("xnbd", paramResultSet.getBigDecimal(5));
										coinMap.put("xnbz", paramResultSet.getBigDecimal(6));
										coinMap.put("jia", paramResultSet.getBigDecimal(7));
										coinMap.put("zhehe", paramResultSet.getBigDecimal(8));
										map.put(name, coinMap);
									}
									return map;
								}

							}, sb.toString(), userId, m.get("marketId"));
					coinList.putAll(coinMap);
				}
				result.put("coinList", coinList);
			}
		}

		return result;
	}

	@Override
	public Integer getUserId(String apikey) throws Throwable {
		return selectInt(P2PConst.DB_USER, "select f01 from t6010 where f12 = 'S' and F13 = ?", apikey);
	}

	@Override
	public Map<String, Object> getUserCny(String apikey) throws Throwable {
		int userId = getUserId(apikey);
		Map<String, Object> result = new HashMap<>();
		if (userId > 0) {
			StringBuffer sb = new StringBuffer();
			sb.append("SELECT F02 ZJ,F03 DJ,F04 KY FROM T6023 WHERE F01=?");
			Map<String, Object> coinMap = select(getConnection(P2PConst.DB_USER),
					new ItemParser<Map<String, Object>>() {
						@Override
						public Map<String, Object> parse(ResultSet paramResultSet) throws SQLException {
							Map<String, Object> coinMap = new HashMap<>();
							if (paramResultSet.next()) {
								coinMap.put("zj", paramResultSet.getBigDecimal(1));
								coinMap.put("dj", paramResultSet.getBigDecimal(2));
								coinMap.put("ky", paramResultSet.getBigDecimal(3));
							}
							return coinMap;
						}

					}, sb.toString(), userId);
			String baseCoin = selectString(P2PConst.DB_USER, "SELECT F02 FROM T6013 WHERE F01=?", "0");
			if (StringHelper.isEmpty(baseCoin)){
				baseCoin = "cny";
			}
			result.put(baseCoin, coinMap);
		}
		return result;
	}

	@Override
	public XxcsEntity[] xxcsSearch(int scid, IsPass is) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		int bid = getBid(scid);
		return selectAll(getConnection(P2PConst.DB_USER), new ArrayParser<XxcsEntity>() {
			ArrayList<XxcsEntity> list = new ArrayList<XxcsEntity>();

			@Override
			public XxcsEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					XxcsEntity x = new XxcsEntity();
					x.id = re.getInt(1);
					x.bid = re.getInt(2);
					x.sfdx = EnumParser.parse(IsPass.class, re.getString(3));
					x.nr = re.getString(4);
					x.sfxs = EnumParser.parse(IsPass.class, re.getString(5));
					x.px = re.getInt(6);
					x.linkNameOrParamEn = re.getString(7);
					x.linkNameOrParamTw = re.getString(8);
					list.add(x);
				}
				return list == null ? null : list.toArray(new XxcsEntity[list.size()]);
			}
		}, "SELECT F01,F02,F03,F04,F05,F06,F07,F08 FROM  T6013_1 WHERE F02=? AND F05=? AND F03=? ORDER BY F06 DESC", bid,
				IsPass.S, is);
	}

	@Override
	public void addPj(int scid, String nr, int js, int yy, int qj) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		int bid = getBid(scid);
		if (StringHelper.isEmpty(nr)) {
			throw new ParameterException("err_1071");
		}
		if (!StringHelper.formatChikcZr(nr)) {
			throw new ParameterException("err_1072");
		}
		int userid = serviceResource.getSession().getAccountId();
		execute(getConnection(P2PConst.DB_USER),
				"INSERT INTO T6013_3 SET F02=?,F03=?,F04=?,F05=CURRENT_TIMESTAMP(),F09=?", bid, userid, nr, IsPass.S);
		int count = selectInt(P2PConst.DB_USER, "SELECT COUNT(F02) FROM T6013_5 WHERE F02=?", bid);
		if (count > 0) {
			execute(getConnection(P2PConst.DB_USER),
					"UPDATE T6013_5 SET F03=F03+1,F04=F04+?,F05=F05+?,F06=F06+? WHERE F02=?", js, yy, qj, bid);
		} else {
			execute(getConnection(P2PConst.DB_USER), "INSERT INTO T6013_5 SET F02=?,F03=1,F04=?,F05=?,F06=? ", bid, js,
					yy, qj);
		}
		execute(getConnection(P2PConst.DB_USER),
				"INSERT INTO T6013_6 SET F02=?,F03=?,F04=?,F05=?,F06=?,F07=CURRENT_TIMESTAMP()", bid, userid, js, yy,
				qj);
	}

	@Override
	public PagingResult<PjEntity> searchPj(int scid, Paging paging) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		int bid = getBid(scid);
		return selectPaging(getConnection(P2PConst.DB_USER), new ArrayParser<PjEntity>() {
			ArrayList<PjEntity> list = new ArrayList<PjEntity>();

			@Override
			public PjEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					PjEntity x = new PjEntity();
					x.id = re.getInt(1);
					x.nr = re.getString(2);
					x.iphone = re.getString(3);
					x.sj = re.getTimestamp(4);
					x.hao = re.getInt(5);
					x.zhong = re.getInt(6);
					x.cha = re.getInt(7);
					list.add(x);
				}
				return list == null ? null : list.toArray(new PjEntity[list.size()]);
			}
		}, paging,
				"SELECT T6013_3.F01,T6013_3.F04,T6010.F02,T6013_3.F05,T6013_3.F06,T6013_3.F07,T6013_3.F08 FROM T6013_3 LEFT JOIN T6010 ON T6013_3.F03=T6010.F01 WHERE T6013_3.F02=? AND T6013_3.F09=? ORDER BY T6013_3.F05 DESC ",
				bid, IsPass.S);
	}

	@Override
	public PjEntity pf(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		int bid = getBid(scid);
		return select(getConnection(P2PConst.DB_USER), new ItemParser<PjEntity>() {

			@Override
			public PjEntity parse(ResultSet re) throws SQLException {
				PjEntity x = new PjEntity();
				while (re.next()) {
					x.tprs = re.getInt(1);
					x.js = re.getInt(2);
					x.yy = re.getInt(3);
					x.qj = re.getInt(4);
				}
				return x;
			}
		}, "SELECT F03,F04,F05,F06 FROM T6013_5 WHERE F02=?", bid);
	}

	@Override
	public void dz(int pjid, int type) throws Throwable {

		if (pjid <= 0) {
			return;
		}
		if (type <= 0) {
			return;
		}
		execute(getConnection(P2PConst.DB_USER), "INSERT INTO T6013_4 SET F02=?,F03=?,F04=?,F05=CURRENT_TIMESTAMP()",
				pjid, serviceResource.getSession().getAccountId(), type);
		StringBuilder s = new StringBuilder("UPDATE T6013_3 SET");
		if (type == 1) {
			s.append(" F06=F06+1");
		}
		if (type == 2) {
			s.append(" F07=F07+1");
		}
		if (type == 3) {
			s.append(" F08=F08+1");
		}
		s.append(" WHERE F01=?");

		execute(getConnection(P2PConst.DB_USER), s.toString(), pjid);
	}

	@Override
	public int conut(int pjid) throws Throwable {

		return selectInt(P2PConst.DB_USER, "SELECT COUNT(F02) FROM T6013_4 WHERE F02=? AND F03=?", pjid,
				serviceResource.getSession().getAccountId());
	}

	@Override
	public ZhEntity getZh(int scid) throws Throwable {
		ZhEntity z = new ZhEntity();
		try (Connection connection = getConnection(P2PConst.DB_USER)) {
			try (PreparedStatement ps = connection.prepareStatement("SELECT F03,F04 FROM T6023 WHERE F01=?")) {// 锁市场表
				ps.setInt(1, serviceResource.getSession().getAccountId());
				try (ResultSet re = ps.executeQuery()) {
					while (re.next()) {
						z.cny_dj = Formater.formatAmount(re.getBigDecimal(1));
						z.cny_ky = Formater.formatAmount(re.getBigDecimal(2));
						z.cny_ky_js = String.valueOf(re.getBigDecimal(2));
					}
				}
			}
		}
		UserZhEntity x = getZhXlb(scid);
		int ws = selectInt(P2PConst.DB_USER, "SELECT F05 FROM T6015 WHERE F01=?", scid);
		z.xlb_dj = Formater.formatAmount_(x.xlb_dj, ws);
		z.xlb_ky = x.xlb_ky.setScale(ws, BigDecimal.ROUND_DOWN).toString();
		z.xlb_ky_js = String.valueOf(x.xlb_ky);
		
		//币币交易使用
		Map<String,Double> buyBalance = getBuyBalance(scid);
		double uv= 0,fv=0;
		if(buyBalance.size()>0) {
			uv = buyBalance.get("usable_virtualCoin");
			fv = buyBalance.get("frozen_virtualCoin");
		}
		z.usable_virtualCoin = uv;
		z.frozen_virtualCoin = fv;
		return z;
	}
	
	/*
	 * 币币交易中使用
	 * 获取买方币可用余额和冻结余额
	 * */
	private Map<String,Double> getBuyBalance(int scid) throws Throwable {
		if (scid <= 0) {
			throw new ParameterException("err_1023");
		}
		int buyCoinId = getBuyBid(scid);
		if (buyCoinId < 0) {
			throw new ParameterException("err_1025");
		}
		StringBuffer sql = new StringBuffer("SELECT T6025.F03 bid,T6025.F04 ky,T6025.F05 dj");
		sql.append(" FROM T6025 LEFT JOIN T6013 ON T6025.F03=T6013.F01");
		sql.append(" WHERE  T6025.F02=? AND T6025.F03=?");
		return this.select(getConnection(P2PConst.DB_USER), new ItemParser<Map<String,Double>>() {

			@Override
			public Map<String,Double> parse(ResultSet rs) throws SQLException {
				Map<String,Double> m = new HashMap<String,Double>(1);
				while (rs.next()) {
					m.put("usable_virtualCoin", rs.getDouble(2));
					m.put("frozen_virtualCoin", rs.getDouble(3));
				}
				return m;
			}
		}, sql.toString(), serviceResource.getSession().getAccountId(), buyCoinId);

	}
	
	/*
	 * 获取买方币ID
	 * */
	private int getBuyBid(int scid) throws Throwable {
		if (scid <= 0) {
			return 0;
		}
		return selectInt(P2PConst.DB_USER, "SELECT F03 FROM T6015 WHERE F01=?", scid);
	}

	@Override
	public List<Map<String, Object>> queryOrder(String name, String apikey) throws Throwable {
		StringBuffer sql = new StringBuffer("SELECT DATE_FORMAT(T6017.F09,'%m-%d %H:%i:%s') sj,");
		sql.append("IF (T6017.F07 = 'MR', 1, 2) zt,T6017.F04 jg,T6017.F05 sl,");
		sql.append(" 	T6017.F06 ycjsl,T6017.F01 id ");
		sql.append("  	FROM T6017 ");
		sql.append("  	WHERE 1=1");
		sql.append("  	AND T6017.F02=? AND T6017.F03=? AND T6017.F08=? ");
		sql.append(" ORDER BY T6017.F09 DESC");
		int userid = getUserId(apikey);
		if (userid <= 0) {
			throw new ParameterException("err_1021");
		}
		List<Map<String, Object>> listMarkMap = getMarket(name);
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		if (listMarkMap != null && listMarkMap.size() > 0) {
			for (Map<String, Object> m : listMarkMap) {
				result = select(getConnection(P2PConst.DB_USER), new ItemParser<List<Map<String, Object>>>() {
					@Override
					public List<Map<String, Object>> parse(ResultSet re) throws SQLException {
						List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
						while (re.next()) {
							Map<String, Object> m = new HashMap<>();
							m.put("addtime", re.getString(1));
							m.put("type", re.getInt(2));
							m.put("price", re.getBigDecimal(3));
							m.put("num", re.getBigDecimal(4));
							m.put("deal", re.getBigDecimal(5));
							m.put("id", re.getInt(6));
							list.add(m);
						}
						return list;
					}
				}, sql.toString(), Integer.parseInt(m.get("marketId").toString()), userid, EntrustType.JYZ);
				break;
			}
		}
		return result;
	}

	@Override
	public Map<String, Object> getMyTradeLog(String name, String apikey) throws Throwable {
		StringBuffer sql = new StringBuffer("SELECT DATE_FORMAT(F11,'%m-%d %H:%i:%s') addtime ");
		sql.append(",IF (F10 = 'MR', 'buy', 'sell') type,F05 price,F06 num,F07 mum from t6018");
		sql.append(" where F02=? and (F03=? or F04 = ?)");
		int userid = getUserId(apikey);
		if (userid <= 0) {
			throw new ParameterException("err_1021");
		}
		List<Map<String, Object>> listMarkMap = getMarket(name);
		Map<String, Object> result = new HashMap<>();
		if (listMarkMap != null && listMarkMap.size() > 0) {
			for (Map<String, Object> m : listMarkMap) {
				List<Map<String, Object>> list = select(getConnection(P2PConst.DB_USER),
						new ItemParser<List<Map<String, Object>>>() {
							@Override
							public List<Map<String, Object>> parse(ResultSet re) throws SQLException {
								List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
								while (re.next()) {
									Map<String, Object> m = new HashMap<>();
									m.put("addtime", re.getString(1));
									m.put("type", re.getString(2));
									m.put("price", re.getBigDecimal(3));
									m.put("num", re.getBigDecimal(4));
									m.put("mum", re.getBigDecimal(5));
									list.add(m);
								}
								return list;
							}
						}, sql.toString(), Integer.parseInt(m.get("marketId").toString()), userid, userid);
				result.put(m.get("marketName").toString(), list);
			}
		}
		return result;
	}
	
	@Override
	public String getOrdinaryList(long market, long time) throws Throwable {
		long minutm = time / 60;
		String table_name = "";
		if (minutm >= 60 && minutm < 360) {
			table_name = P2PConst.DB_USER+".t6019_market_n";
		} else if (minutm >= 360) {
			table_name = P2PConst.DB_USER+".t6019_market_m";
		} else {
			table_name = String.format(P2PConst.DB_USER+".t6019_%d%s%d", market, '_', time);
		}

		StringBuffer sql = new StringBuffer("SELECT F10 FROM");
		sql.append("  " + table_name);
		sql.append(" where F12=? AND F11=? order by F08 desc ");
		sql.append(" LIMIT 1000");
		Object[] parameters = new Object[2];
		parameters[0] = market;
		parameters[1] = time;
		StringBuilder resultString = new StringBuilder("[");
		try (PreparedStatement pstmt = getConnection(P2PConst.DB_USER).prepareStatement(sql.toString());) {
			serviceResource.setParameters(pstmt, parameters);
			try (ResultSet resultSet = pstmt.executeQuery();) {
				while (resultSet.next()) {
					String str = resultSet.getString(1);
					str=str.replaceAll("[\\[\\]]", "");
					String[] strs = str.split(",");
					String newStr = "["+strs[0]+","+strs[7]+","+strs[3]+","+strs[5]+","+strs[6]+","+strs[4]+"]";//0,7,3,5,6,4
					resultString.insert(1, newStr + ",");
				}
			}
		}

		String s = resultString.toString();
		if (s.length() > 2)
			s = s.substring(0, s.length() - 1);
		s += ("]");
		return s;
	}

	@Override
	public List<HashMap<String, Object>> getUserAccount(int id) throws Throwable {
		List<HashMap<String, Object>> res = new ArrayList<>();
		String sql = "select t6013.f02,IFNULL(a.f04,'0'),IFNULL(a.f05,'0') from t6013 "
				+ "LEFT JOIN (select * from t6025 where t6025.f02=?) a "
				+ "on t6013.F01 = a.f03 where t6013.f01!=16 "
				+ "union all (select (select f02 from t6013 where f01=16),"
				+ "f04,f03 from t6023 where f01=?);";
		Object[] parameters = new Object[2];
		parameters[0] = id;
		parameters[1] = id;
		try (PreparedStatement pstmt = getConnection(P2PConst.DB_USER).prepareStatement(sql.toString());) {
			serviceResource.setParameters(pstmt, parameters);
			try (ResultSet rst = pstmt.executeQuery()) {
				while (rst.next()) {
					HashMap<String, Object> map = new HashMap<>();
					map.put("coinShortName", rst.getString(1));
					map.put("available", rst.getString(2));
					map.put("frozen", rst.getString(3));
					res.add(map);
				}
			}
		}
		return res;
	}
	
	@Override
	public String getBrokenLine(int marketId, int days) throws Throwable {
		StringBuilder strs = new StringBuilder("[");
		Object[] parameters = new Object[1];
		parameters[0] = marketId;
		//parameters[1] = days;
		String sql="SELECT F03 AS str FROM T6021 WHERE F02 = ?";
		try (PreparedStatement pstmt = getConnection(P2PConst.DB_USER).prepareStatement(sql.toString());) {
			serviceResource.setParameters(pstmt, parameters);
			try (ResultSet resultSet = pstmt.executeQuery();) {
				while (resultSet.next()) {
					if(null!=resultSet.getString(1))
						strs.append(resultSet.getString(1));					
				}
			}
		}
		strs.append("]");
		return strs.toString();
	}
	
}